<template>

  <el-dialog
      append-to-body
      :title="'请选择角色【'+roleModel.name+'】的权限'"
      :visible.sync="dialogVisible"
      width="70%"
      @close="dialogClose"
      rihgt>
    <el-container style="">
      <el-aside width="300px" class="border " style="border-right-width: 0px">
        <div class="title  el-button--primary">功能权限</div>
        <div style="overflow: scroll;max-height: 400px">
          <el-input
              placeholder="输入关键字进行过滤"
              v-model="searchMenuName">
          </el-input>
          <el-tree
              empty-text="正在加载菜单中"
              :data="currentUserMenuData"
              show-checkbox
              node-key="id"
              ref="tree"
              :filter-node-method="treeMenuSearch"
              highlight-current
              @node-click="handleNodeClick"
              :props="defaultProps"></el-tree>
        </div>

      </el-aside>
      <el-main class="border">
        <div class="title  el-button--primary">数据权限</div>
        <avue-crud :data="ruleDataSource" ref="crud" :option="ruleDataOption" :refresh-change="loadDataRulesByMenuId"
                   :tableLoading="ruleDataLoading">

        </avue-crud>
      </el-main>
    </el-container>
    <div slot="footer" class="dialog-footer" style="text-align: right;display: block;">
      <el-button style="margin-left: 10px;margin-right: 10px;" @click="dialogVisible = false">取 消</el-button>
      <el-button style="margin-left: 10px;margin-right: 10px; " type="primary" @click="saveMenu">保存角色功能菜单</el-button>
      <el-button :disabled="!currentCheckedKeys.includes(currentSelectMenuId)"
                 style="margin-left: 10px;margin-right: 10px; " type="primary" @click="saveRoleMenuDataRule">保存数据权限
      </el-button>
    </div>
  </el-dialog>

</template>

<script>
import {getCurrentUserMenu, getRoleMenu, saveRoleMenu} from "@/api/sys/roleApi";
import treeUtils from "@/utils/treeUtils";
import {getDataRulesByMenuId} from "@/api/sys/dataRuleApi";
import {getDataRuleListByRoleMenu, saveDataRules} from "@/api/sys/ruleDataRuleApi";
import {Loading} from 'element-ui';

export default {
  name: "editor-permission-dialog",
  props: {},

  computed: {
    ruleDataOption() {
      return {
        page: false,
        align: 'center',
        dateBtn: false,
        dateDefault: true,
        menu: false,
        addBtn: false,
        selection: true,
        menuPosition: 'right',
        columnBtn: false,
        menuAlign: 'center',
        column: [
          {
            label: '名称',
            prop: 'ruleName'
          },]
      }
    }
  },
  watch: {
    searchMenuName(val) {
      this.$refs.tree.filter(val);
    }
  },
  data() {
    return {
      dialogVisible: false,
      currentUserMenuData: [],
      targetRoleMenu: [],
      currentCheckedKeys: [],
      currentSelectMenuId: '',
      searchMenuName: null,
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      roleId: null,
      roleModel: {name: ''},
      ruleDataSource: [],
      ruleDataLoading: false,
    }
  },
  created() {
    this.loadUserMenu();
  },
  methods: {
    treeMenuSearch(val, data) {
      if (!val) return true;
      return data[this.defaultProps.label].indexOf(val) > -1;
    },
    show(row) {
      this.roleId = row.id;
      this.roleModel = row;
      this.dialogVisible = true
      this.$nextTick(this.loadRoleMenu())
    },
    loadUserMenu() {
      getCurrentUserMenu().then(res => {
        let data = res.data.data;
        this.currentUserMenuData = treeUtils.listToTree(data)
      })
    },
    handleNodeClick(data, node) {
      this.ruleDataSource = [];
      this.ruleDataLoading = true;
      this.currentSelectMenuId = data.id;
      this.$refs.crud.selectClear();
      this.loadDataRulesByMenuId();

    },
    loadDataRulesByMenuId() {
      getDataRulesByMenuId(this.currentSelectMenuId).then(res => {
        this.ruleDataSource = res.data.data;
        this.loadDataRuleListByRoleMenu(this.ruleDataSource, this.currentSelectMenuId);
      }).finally(() => this.ruleDataLoading = false)
    },
    loadDataRuleListByRoleMenu(dataSource, menuId) {
      this.$refs.crud.selectClear();
      if (!dataSource) return;
      getDataRuleListByRoleMenu(this.roleId, menuId).then(res => {
        let selectsRow = res.data.data;
        if (!selectsRow) return
        for (let i = 0; i < selectsRow.length; i++) {
          let index = dataSource.findIndex(item => item.id === selectsRow[i].dataRuleId)
          if (index === undefined) continue;
          let row = dataSource[index];
          this.$refs.crud.$refs.table.toggleRowSelection(row)
        }
      })
    },
    loadRoleMenu() {
      this.targetRoleMenu = []
      this.currentCheckedKeys = [];
      getRoleMenu(this.roleId).then(res => {
        let data = res.data.data;

        // let ids = [];
        for (let i = 0; i < data.length; i++) {
          // ids.push(data[i].id)
          this.currentCheckedKeys.push(data[i].id)
        }
        // this.currentCheckedKeys = ids;
        let temp = this.resolveAllEunuchNodeId(this.currentUserMenuData, this.currentCheckedKeys, [])
        this.$refs.tree.setCheckedKeys(temp);
      })
    },
    /**
     * 解析出所有的太监节点id
     * @param treeData 待解析的json串
     * @param idArr 原始节点数组
     * @param temp 临时存放节点id的数组
     * @return 太监节点id数组
     */
    resolveAllEunuchNodeId(treeData, idArr, temp) {
      // console.log("开始遍历")
      for (let i = 0; i < treeData.length; i++) {
        const item = treeData[i]
        // 存在子节点，递归遍历;不存在子节点，将json的id添加到临时数组中
        if (item.children && item.children.length !== 0) {
          this.resolveAllEunuchNodeId(item.children, idArr, temp)
        } else {
          temp.push(idArr.filter(id => id === item.id))
        }
      }
      return temp
    },
    dialogClose() {
      this.$refs.tree.setCheckedKeys([]);
      this.ruleDataSource = [];
    },
    saveMenu() {
      let keys = this.$refs.tree.getCheckedKeys();
      let temp = this.$refs.tree.getHalfCheckedKeys();
      // console.log(temp)
      let menuIds = keys.concat(keys, temp);

      let data = {};
      data.roleId = this.roleId;
      data.menuIds = menuIds;
      let saveLoading = Loading.service({fullscreen: true, text: '保存中',background:"#0008"})
      saveRoleMenu(data).then(res => {
        this.$message.success('保存成功');
        this.loadRoleMenu();
      }).finally(() => {
        saveLoading.close()
      })
    },
    saveRoleMenuDataRule() {
      let curd = this.$refs.crud;
      let selectionRows = curd.$refs.table.selection;
      let ids = [];
      for (let i = 0; i < selectionRows.length; i++) {
        ids.push(selectionRows[i].id);
      }
      saveDataRules(this.roleId, this.currentSelectMenuId, ids).then(res => {
        this.$message.success("数据规则保存成功");
      }).finally(() => this.loadDataRuleListByRoleMenu(this.ruleDataSource, this.currentSelectMenuId))
    },
  }
}
</script>

<style scoped lang="scss">

.title {
  padding: 5px;
  text-align: center;
  border: 5px;

}

.border {
  border: #ccc 1px solid;
}

</style>
